package main

import (
	"time"

	"github.com/gin-contrib/cors"
	"gorm.io/gorm"

	"github.com/lab-online/pkg/database"
	"github.com/lab-online/pkg/e2e"
	"github.com/lab-online/pkg/logger"
	"github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/mq"

	"github.com/lab-online/config"
	app "github.com/lab-online/internal"
)

func setupServer() *e2e.Config {
	db := database.ConnectDB(config.Service.Postgres, &gorm.Config{
		Logger: logger.NewGORMLogger(*config.GORMLogger),
	})
	messageQueue := mq.Connect(config.Service.RabbitMQ)

	db.Exec("DELETE FROM users")
	db.Exec("DELETE FROM classes")

	corsConfig := cors.DefaultConfig()
	corsConfig.AllowOrigins = config.CORS.AllowOrigins
	corsConfig.AllowMethods = config.CORS.AllowMethods
	corsConfig.AllowHeaders = config.CORS.AllowHeaders
	corsConfig.AllowCredentials = config.CORS.AllowCredentials
	corsConfig.MaxAge = config.CORS.MaxAge * time.Minute

	server := app.New(&app.Config{
		Database:     db,
		MessageQueue: messageQueue,
		JWT:          config.JWT,
		CORS:         corsConfig,
		Mode:         config.Server.Mode,
		HttpLogger: middleware.LoggerConfig{
			Console: &config.Logger.ConsoleHttp,
			Level:   &config.Logger.HttpLevel,
		},
	})

	if err := server.Migrate(); err != nil {
		logger.Warn("failed to migrate database")
		logger.Warn(err.Error())
	}

	server.RegisterRoutes(config.Server.Prefix)

	return &e2e.Config{
		Prefix:   config.Server.Prefix,
		Server:   server.GetEngine(),
		JWT:      config.JWT,
		Database: db,
	}
}
